package com.sf.marathon.soul.core.web;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;

import com.sf.marathon.soul.core.util.SignUtils;
import com.sf.marathon.soul.core.util.StringUtils;

import lombok.extern.slf4j.Slf4j;

/**
 * 登录认证的过滤器
 */
@Component
@WebFilter(urlPatterns = "/*", filterName = "accessControlFilter")
@Slf4j
public class AccessControlFilter implements Filter {

    /**
     * 不需要过滤的url列表
     */
    protected static String[] excludeUrls = {".*/user/login.*", ".*/images/*.*"};

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
        log.info("accessControlFilter。。。。request url is {}", httpRequest.getRequestURI());
        String url = httpRequest.getRequestURI().substring(httpRequest.getContextPath().length());
        boolean isExclude = isExcludeUrl(url);
        if (isExclude) {
            chain.doFilter(httpRequest, httpResponse);
            return;
        } else {
            String xToken = httpRequest.getHeader("x-token");
            if (StringUtils.isEmpty(xToken) || SignUtils.xTokens.get(xToken) == null) {
                SignUtils.responseRedirectJson(httpResponse, "decided by you");
                log.info("accessControlFilter no login。。。。request url is {}", httpRequest.getRequestURI());
                return;
            }
            // 判断有效期
            Long loginTime = SignUtils.xTokens.get(xToken);
            boolean isAlive = (System.currentTimeMillis() - loginTime) < 1800000;
            if (isAlive) {
                SignUtils.xTokens.put(xToken, System.currentTimeMillis());
            } else {
                SignUtils.xTokens.remove(xToken);
                SignUtils.responseRedirectJson(httpResponse, "decided by you");
                log.info("accessControlFilter no login。。。。request url is {}", httpRequest.getRequestURI());
                return;
            }
            chain.doFilter(httpRequest, httpResponse);
            return;
        }
    }

    @Override
    public void destroy() {
        // TODO method should not empty
    }

    private boolean isExcludeUrl(String url) {
        for (String excludeUrl : excludeUrls) {
            Pattern p = Pattern.compile(excludeUrl);
            Matcher matcher = p.matcher(url);
            if (matcher.matches()) {
                return true;
            }
        }
        return false;
    }
}
